package loginController

import (
	"arabApi/app/api/controllers"
	"arabApi/app/api/controllers/CFun"
	"arabApi/app/api/models/userModel"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/loginRequest"
	"arabApi/app/api/services/LoginService"
	redis2 "arabApi/pkg/redis"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/spf13/cast"
)

// Login 注册控制器
type Login struct {
	controllers.BaseAPIController
}

var LoginRedis = "login_token"

// Login 登录
func (r Login) Login(c *gin.Context) {

	request := loginRequest.LoginRequest{}

	// 解析 JSON 请求
	if err := c.ShouldBindBodyWith(&request, binding.JSON); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("1"+err.Error()))
		return
	}
	if ok := requests.Validate(c, &request, loginRequest.CheckLogin); !ok {
		return
	}

	user := LoginService.Login(request.User)
	if ok := LoginService.CheckPwd(user.Password, request.Pwd); !ok {
		CFun.Ajax_return_fail(c, CFun.WithMsg("账号或密码错误"))
		return
	}

	token := LoginService.GetToken(user.ID)
	redis2.Redis.Set(LoginRedis+cast.ToString(user.ID), token, r.GetRedisTime())

	data := make(gin.H)
	data["token"] = token
	data["uid"] = user.ID

	CFun.Ajax_return_success(c, CFun.WithData(data))
}

func (r Login) UserMsg(id int64) userModel.User {
	user := LoginService.UserMsgById(id)
	return user
}
